<script setup>
import { getCurrentInstance, ref, computed, nextTick } from 'vue'
import BaseQueryTable from '@shared/base/base-query-table/index.vue'
import { useBaseQueryTable } from '@shared/base/base-query-table/use-table'
import { Search, Close } from '@element-plus/icons-vue'
import { highlightSearchResults } from '@shared/base/base-highlight/highlight'

const { proxy } = getCurrentInstance()
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits([])

/* 状态 */
const authTableRef = ref()

/**
 * 搜索内容
 */
const searchValue = ref('')

const useTable = useBaseQueryTable({
  showPagination: false,
  elTableAttrs: {
    rowKey: (row) => row.empName + row.empCode
  },
  isViewportFitHeight: true,
  columns: [
    { type: 'selection', width: '56', fixed: 'left', 'reserve-selection': true },
    { label: '姓名', prop: 'empName', minWidth: 76, className: 'ijep-cell-name' },
    { label: '手机号', prop: 'mobile', minWidth: 120, className: 'ijep-cell-mobile' },
    {
      label: '角色',
      prop: 'roleList',
      minWidth: 100,
      transformText: ({ cellValue }) => cellValue?.map((role) => role.roleName).join('、')
    }
  ]
})

/* 方法 */
function onSearch() {
  CSS?.highlights?.clear()

  // 获取搜索内容
  const inputValue = searchValue.value.trim()
  if (!inputValue) return

  // 获取表格容器
  const tableContainer = authTableRef.value
  if (!tableContainer) return

  // 下一帧再高亮，dom 渲染完再高亮
  nextTick(() => {
    // 获取所有名字的节点  ijep-cell-name 是自己加的 类样式
    const nameCells = Array.from(tableContainer.querySelectorAll('.ijep-table__row .ijep-cell-name .cell'))
    // 获取所有手机号的节点  ijep-cell-mobile 是自己加的 类样式
    const mobileCells = Array.from(tableContainer.querySelectorAll('.ijep-table__row .ijep-cell-mobile .cell'))

    highlightSearchResults([...nameCells, ...mobileCells], inputValue)
  })
}

/**
 * 重置搜索
 */
function onClear() {
  searchValue.value = ''
  CSS?.highlights?.clear()
}

/* 计算 */

/* 监听 */

/* 周期 */
/**
 * 过滤数据
 * @type {ComputedRef<*>}
 * @private
 */
const _dataList = computed(() => {
  return props.data.filter((item) => {
    // 没有值，返回true
    if (!searchValue.value) return true

    // 如果没有值，返回true
    if (searchValue.value && !item.empName && !item.mobile) return false
    return item.empName?.includes(searchValue.value) || item.mobile?.includes(searchValue.value)
  })
})

/* 暴露 */
defineExpose({
  $: proxy.$,
  get checkedRowList() {
    return useTable.baseTableRef.checkedRowList
  },
  clearCheckedRowList() {
    useTable.baseTableRef.elTableRef.clearSelection()
  }
})
</script>

<template>
  <div
    ref="authTableRef"
    class="auth-table flex flex-col gap-3"
  >
    <el-input
      v-model="searchValue"
      class="flex-none"
      placeholder="请输入（姓名或手机号）"
      @input="onSearch"
    >
      <template #suffix>
        <Search
          v-if="searchValue.length === 0"
          class="w-16px h-16px"
        />
        <Close
          v-else
          class="w-16px h-16px header__icon--clear cursor-pointer"
          @click="onClear"
        />
      </template>
    </el-input>

    <BaseQueryTable
      class="flex-1"
      v-bind="useTable"
      :data="_dataList"
    />
  </div>
</template>

<style scoped lang="less">
::highlight(search-results) {
  color: var(--tzx-primary-color, #2d49d1);
  background-color: var(--tzx-primary-color-50, #e9ecfa);
}
</style>
